import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class SimpleChatClient extends JFrame implements ActionListener {

   JPanel pnMsg = new JPanel();

   JLabel lbName = new JLabel( "Name: " );
   JLabel lbMsg = new JLabel( "Message: " );
   JTextField tfName = new JTextField("JD", 6);
   JTextField tfMsg = new JTextField("Howdy.", 25 );
   JTextArea  taMsgs = new JTextArea();
   JButton    btnCmd = new JButton("Send");

   Socket sk = null;
   ObjectOutputStream out = null;
   ObjectInputStream  in  = null;

   public void  actionPerformed (ActionEvent e ) {
	System.out.println("Button clicked");
	new Messager( tfName.getText() + " : " + tfMsg.getText(), out ).start();
   }
 
   public SimpleChatClient() {
	setTitle("Chatroom client program");
	setSize(600, 400);
	Container c = getContentPane();
	c.add(taMsgs, BorderLayout.CENTER );
	pnMsg.add( lbName );
	pnMsg.add( tfName );
	pnMsg.add( lbMsg);
	pnMsg.add( tfMsg);
	pnMsg.add( btnCmd );
	btnCmd.addActionListener( this );
	c.add(pnMsg, BorderLayout.SOUTH);
	show();
	try {
		sk = new Socket("sumatra.cs.csubak.edu", 2199);
		out = new ObjectOutputStream( sk.getOutputStream() );
		in = new ObjectInputStream( sk.getInputStream() );
		new ClientAgent( taMsgs, in).start();

	} catch (Exception e) { e.printStackTrace(); }
   }

   public static void main(String args[] ) {
	SimpleChatClient app = new SimpleChatClient();
   }

}

class Messager extends Thread {

  String msg = null;
  ObjectOutputStream out = null;

  public Messager( String m, ObjectOutputStream o ) { msg = m; out = o; }

  public void run( ) {
     try {
	out.writeObject( msg );
     } catch (Exception e ) { e.printStackTrace(); }
  }
}
	
class ClientAgent extends Thread {

   ObjectInputStream in = null;
   JTextArea taMsgs = null;

   public ClientAgent( JTextArea ta, ObjectInputStream i) {
	in = i; taMsgs = ta;
   }

   public void run() {
     try {
	System.out.println("Client agent is running.");
	while (true )
		taMsgs.append( in.readObject() + "\n");

     } catch (Exception e) { e.printStackTrace(); }
     System.out.println("Client agent ended");
  }
}


